import java.util.Map;
import java.util.concurrent.locks.StampedLock;

/**
 * @Author Stringzhua
 * @Date 2024/11/4 10:29
 * description:
 */
public class Demo04 {
    private double x;
    private double y;

    public final StampedLock lock = new StampedLock();

    //写入操作
    public void move(double rx, double ry) {
        //获取写锁
        long stamp = lock.writeLock();
        try {
            x += rx;
            y += ry;
        } finally {
            lock.unlock(stamp);
        }
    }

    //读取操作
    public double sqrt() {
        //获取乐观读锁
        long stamp = lock.tryOptimisticRead();

        double sqX = x;
        // 此处已读取到x=100，但x,y可能被写线程修改为(300,400)

        double sqY = y;
        // 此处已读取到y，如果没有写入，读取是正确的(100,200)
        // 如果有写入，读取是错误的(100,400)

        //检查乐观锁的stamp值
        //判断是否在读取时发生写入操作
        if (!lock.validate(stamp)) {
            //获取悲观读锁
            stamp = lock.readLock();
            try {
                sqX = x;
                sqY = y;
            } finally {
                lock.unlockWrite(stamp);
            }
        }
        return Math.sqrt(sqX * sqX + sqY * sqY);
    }

}
